import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { CapturedPokemon, Pokemon } from '../types/pokemon'
import { StorageKey } from '@/utils/enum'
import default_config from '@/config/default_config'
import { generateCaptureId } from '@/utils'
import dayjs from 'dayjs'

export const useCapturedPokemonStore = defineStore('capturedPokemon', () => {
  const data = ref<{ [key: number]: CapturedPokemon }>({})

  const viewList = computed(() => Object.values(data.value))

  const init = async () => {
    let _data: { [key: number]: CapturedPokemon } = {}

    try {
      const localRs = await localStorage.getItem(
        StorageKey.CAPTURED_POKEMON_DATA
      )
      if (localRs) {
        _data = JSON.parse(localRs)
      } else {
        // @ts-ignore
        _data = default_config.capturedPokemon
      }
      data.value = _data
    } catch (error) {
      console.error(error)
    }
  }

  // 捕获精灵
  const capturePokemon = (pokemon: Pokemon) => {
    let _rs: CapturedPokemon = {
      id: pokemon.id,
      captureId: generateCaptureId(),
      currentWork: [],
      currentSatiety: 50,
      captureTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    data.value[_rs.id] = _rs
  }

  return {
    data,
    viewList,
    init,
    capturePokemon,
  }
})
